package com.tourscool.springboot.starter.inquiry.service;

import com.tourscool.springboot.starter.inquiry.core.RequestMethodItem;
import com.tourscool.springboot.starter.inquiry.utils.EncryptUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.stream.Collectors;

/**
 * @author Cedric
 * @date 2020/10/29 16:06
 * @description 服务收集处理类
 */
@Slf4j
@Service
public class CollectService {

    @Autowired
    private HttpServletRequest request;

    private Map<String, List<RequestMethodItem>> serviceInterfaceMap = new ConcurrentHashMap<>();

    public Boolean collect(List<RequestMethodItem> requestMappingMethodList) {

        if (CollectionUtils.isEmpty(requestMappingMethodList)) {
            log.info(request.getServerName() + ":上传接口列表为空");
            return Boolean.FALSE;
        }

        String cServiceName = requestMappingMethodList.get(0).getCServiceName();
        serviceInterfaceMap.remove(cServiceName);
        serviceInterfaceMap.put(cServiceName, requestMappingMethodList);
        return Boolean.TRUE;
    }

    public Map<String, List<RequestMethodItem>> getServiceInterfaceMap() {
        Map<String, List<RequestMethodItem>> newServiceInterfaceMap = Collections.synchronizedMap(serviceInterfaceMap);
        List<RequestMethodItem> requestMethodItemList = new ArrayList<>();
        newServiceInterfaceMap.forEach((cServiceName, requestMethodItems) -> requestMethodItemList.addAll(requestMethodItems));
        Map<String, List<RequestMethodItem>> requestMethodItemMap = requestMethodItemList.stream().collect(Collectors.groupingBy(this::getNewKey));
        newServiceInterfaceMap.forEach((key, values) -> values.forEach(value -> {
            if (value.getPServiceName().equals(value.getCServiceName())) {
                List<RequestMethodItem> requestMethodItems = requestMethodItemMap.get(getNewKey(value));
                value.setCServiceName(requestMethodItems.stream().filter(requestMethod ->
                        !requestMethod.getCServiceName().equals(requestMethod.getPServiceName())).map(RequestMethodItem::getCServiceName).collect(Collectors.joining(",")));
            }
        }));
        return newServiceInterfaceMap;
    }

    private String getNewKey(RequestMethodItem requestMethodItem) {
        String key = requestMethodItem.getPServiceName() + requestMethodItem.getRequestUrl() + requestMethodItem.getRequestType() + requestMethodItem.getReturnType();
        return EncryptUtils.md5String(key);
    }
}
